import { defineStore } from 'pinia'
import { createSession, getMessageById } from '@/apis/message'

export const useMessageStore = defineStore('message', {
  state: () => ({
    sessions: [],
  }),

  actions: {
    async loadSessions(uid) {
      const res = await getMessageById(uid)
      if (res.code === '200') {
        this.sessions = res.data
      }
    },

    findSessionByUserId(targetId) {
      console.log('targetId', targetId)
      console.log('所有sessions', this.sessions)
      return this.sessions.find((s) => s.senderId == targetId)
    },

    async createSession(targetId) {
      const res = await createSession(localStorage.getItem('uid'), targetId)
      if (res.code === '200') {
        this.sessions.push(res.data)
        return res.data
      }
      throw new Error('创建失败')
    },
  },
})
